﻿using System.Collections.Generic;
using System.IO;
using System.Text;

using DigitalQuran.IO;

namespace DigitalQuran.Text
{
    /// <summary>
    /// Set of Rules used to Simplify the text
    /// </summary>
    public sealed class SimplificationRule : Dictionary<string, string>
    {
        private SimplificationRule(string name)
        {
            RuleName = name;
        }

        /// <summary>
        /// Gets the Simplification Rule name
        /// </summary>
        public string RuleName { get; private set; }

        /// <summary>
        /// Simplifies the text
        /// </summary>
        /// <param name="text">text to simplify</param>        
        /// <param name="removeShedda">Teel weather to remove shedda from superscriped letter</param>
        /// <returns>Simplified text according to the rules</returns>
        public string SimplifyText(string text, bool removeShedda = false)
        {
            var str = new StringBuilder(text);

            if (RuleName.Contains("Shadda"))
            {
                for (int i = 1; i < str.Length; i++)
                {
                    if (str[i] == 'ّ') // replace shedda with previous letter                        
                        str[i] = str[i - 1];
                }

                if (removeShedda)
                    str.Replace("ّۧ", "ۧ");
            }

            foreach (var rule in this)
            {
                str.Replace(rule.Key, rule.Value);
            }

            return str.ToString();
        }

        /// <summary>
        /// Loads Simplification Rules from File
        /// </summary>
        /// <param name="filePath">Path of file containing rules</param>
        /// <returns>Returns New Instance of SimplifationRule</returns>
        public static SimplificationRule LoadFromFile(string filePath)
        {
            var rules = new SimplificationRule(Path.GetFileNameWithoutExtension(filePath));

            using (StreamReader reader = File.OpenText(filePath))
            {
                string lineText = "";
                int lineNo = 0;
                while ((lineText = reader.ReadLine()) != null)
                {
                    lineNo++;
                    if (lineText.StartsWith("#")) continue;

                    string[] parts = lineText.Split('\t');
                    if (parts.Length == 2)
                    {
                        try
                        {
                            rules.Add(parts[0], parts[1]);
                        }
                        catch { }
                    }
                    else
                    {
                        throw new InvalidFileStructureException(lineNo, lineText, filePath, "Invalid Simplification Rule At Line " + lineNo.ToString());
                    }
                }
            }

            return rules;
        }
    }
}